package com.xywy.bloodandroid.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.os.Environment;

public class NewFileUtil {
	public static final String split = "/xywy/";
	public static final String CACHEUSER = "usercache";

	public static final String MESSAGE_ONLINE = "messgae_online"; // 在线消息缓存

	public static void clearFile(String fileName) {
		try {
			String fileStr = Environment.getExternalStorageDirectory() + split
					+ fileName;
			File file = new File(fileStr);
			if (file.exists()) {

			} else {
				File parentF = file.getParentFile();
				parentF.mkdir();
				file.createNewFile();
			}
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void saveObject(String fileName, Object object) {
		try {
			String fileStr = Environment.getExternalStorageDirectory() + split
					+ fileName;
			File file = new File(fileStr);
			if (file.exists()) {

			} else {
				File parentF = file.getParentFile();
				parentF.mkdir();
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(new File(fileStr));
			ObjectOutputStream os = new ObjectOutputStream(fos);
			os.writeObject(object);
			os.flush();
			os.close();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static Object getObject(String fileName) {
		Object object = null;
		try {
			String fileStr = Environment.getExternalStorageDirectory() + split
					+ fileName;
			File file = new File(fileStr);
			if (file.exists()) {

			} else {
				File parentF = file.getParentFile();
				parentF.mkdir();
				file.createNewFile();
			}
			FileInputStream fins = new FileInputStream(new File(fileStr));
			ObjectInputStream oins = new ObjectInputStream(fins);
			object = oins.readObject();
			oins.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return object;
	}

	public static long getFileTime(String fileName) {
		String fileStr = Environment.getExternalStorageDirectory() + split
				+ fileName;
		File file = new File(fileStr);
		if (file.exists()) {
			return file.lastModified();
		} else {
			return -1;
		}
	}

	public static void clear(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				clear(childFiles[i]);
			}
			file.delete();
		}
	}
}
